package com.h2.ref.server.auth;

import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

public class Authz {
   
   /**
    * Returns the active user on the current thread.
    */
   public static String getActiveUser() {
      SecurityContext context = SecurityContextHolder.getContext();
      if (context != null) {
         Authentication auth = context.getAuthentication();
         return (auth == null) ? null : auth.getName();
      }
      return null;
   }
   
   public static Authentication getAuthentication() {
      return SecurityContextHolder.getContext().getAuthentication();
   }
   
   public static boolean isAnonymous() {
      return isAnonymous(getAuthentication());
   }
   
   public static boolean isAnonymous(Authentication authentication) {
      if (authentication == null) {
         return false;
      }
      return AnonymousAuthenticationToken.class.isAssignableFrom(
            authentication.getClass());
   }
}
